package edu.gatech.gro;

import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import edu.gatech.gro.http.IResponseAdapter;
import edu.gatech.gro.model.NamedList;
import edu.gatech.gro.model.ObjectResponse;

public class NamedListEditActivity extends Activity {

	private static final String TAG = "NAMED_LIST_EDIT_ACTIVITY";

	private static final int ERROR_USERNAME_RULE = 0;
	// private static final int ERROR_ONLINE = 1;

	private static GroceryListManagerApplication app;

	private ProgressDialog mProgressCreation;
	private AlertDialog mAlertDialog;

	private Button mCreateNamedListButton;
	private EditText mName;

	private int mUserId;
	private NamedList mCurrentNamedList;

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		app = (GroceryListManagerApplication) getApplicationContext();

		setContentView(R.layout.named_list_adder);

		mAlertDialog = new AlertDialog.Builder(NamedListEditActivity.this).create();
		mAlertDialog.setButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		mCreateNamedListButton = (Button) findViewById(R.id.namedListAdderCreateNamedListButton);
		mName = (EditText) findViewById(R.id.namedListAdderNamedListText);

		mCurrentNamedList = null;
		Bundle extra = getIntent().getExtras();
		mUserId = extra.getInt("userId");
		if (extra.getBoolean("hasNamedList")) {
			mCurrentNamedList = new NamedList();
			mCurrentNamedList.setId(extra.getInt("listId"));
			mCurrentNamedList.setName(extra.getString("listName"));
			mName.setText(mCurrentNamedList.getName());
			mCreateNamedListButton.setText(R.string.namedListAdderUpdateNamedListButtonLabel);
		}

		mCreateNamedListButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d(TAG, "Create list button clicked!");
				if (mCurrentNamedList == null) {
					saveList();
				} else {
					updateList();
				}
			}
		});
	}

	private boolean saveList() {
		if (mProgressCreation != null && mProgressCreation.isShowing()) {
			return false;
		}

		String name = mName.getText().toString();

		if (!isName(name)) {
			return displayError(ERROR_USERNAME_RULE);
		}

		mCurrentNamedList = new NamedList();
		mCurrentNamedList.setName(name);
		mCurrentNamedList.setUserId(mUserId);

		mProgressCreation = ProgressDialog.show(NamedListEditActivity.this, "", // this.getString(R.string.pleaseWait),
		    this.getString(R.string.progressNamedListCreation), true, false);

		app.saveNamedList(mCurrentNamedList, mNamedListCreatedListener);
		return true;
	}

	private boolean updateList() {
		if (mProgressCreation != null && mProgressCreation.isShowing()) {
			return false;
		}

		String name = mName.getText().toString();

		if (!isName(name)) {
			return displayError(ERROR_USERNAME_RULE);
		}

		mCurrentNamedList.setName(name);
		mCurrentNamedList.setUserId(mUserId);

		mProgressCreation = ProgressDialog.show(NamedListEditActivity.this, "", // this.getString(R.string.pleaseWait),
		    this.getString(R.string.progressNamedListUpdate), true, false);

		app.updateNamedList(mCurrentNamedList, mNamedListUpdatedListener);
		return true;
	}

	private boolean displayError(int errorCode) {
		switch (errorCode) {
			case ERROR_USERNAME_RULE:
				displayError(R.string.errorNameRuleTitle, R.string.errorNameRuleMessage);
				break;
		}
		return false;
	}

	private boolean isName(String name) {
		String pattern = "^([a-zâêîôûŷäëïöüÿéèàçùA-ZÂÊÎÔÛŶÄËÏÖÜŸÉÈÀÇÙ0-9 '\\-]+)$";
		return Pattern.compile(pattern).matcher(name).find();
	}

	/**
	 * Helper function to dismiss a progress dialog
	 * 
	 * @param theProgress
	 *          the progress dialog to dismiss
	 */
	private void dismissProgress(ProgressDialog theProgress) {
		if (theProgress != null && theProgress.isShowing()) {
			theProgress.dismiss();
		}
	}

	private final IResponseAdapter mNamedListCreatedListener = new IResponseAdapter() {

		@Override
		public void onResponse(ObjectResponse response) {
			dismissProgress(mProgressCreation);
			if (response.isSuccessful()) {
				finish();
			} else {
				displayError(R.string.failCreateListTitle, response.getErrorsAsString());
			}
		}
	};

	private final IResponseAdapter mNamedListUpdatedListener = new IResponseAdapter() {

		@Override
		public void onResponse(ObjectResponse response) {
			dismissProgress(mProgressCreation);
			if (response.isSuccessful()) {
				Intent b = new Intent();
				b.putExtra("id", mCurrentNamedList.getId());
				b.putExtra("name", mCurrentNamedList.getName());
				setResult(RESULT_OK, b);
				finish();
			} else {
				displayError(R.string.failUpdateListTitle, response.getErrorsAsString());
			}
		}
	};

	private void displayError(final int titleId, final int messageId) {
		mAlertDialog.setTitle(titleId);
		mAlertDialog.setMessage(this.getString(messageId));
		mAlertDialog.show();
	}

	private void displayError(final int titleId, final String message) {
		mAlertDialog.setTitle(titleId);
		mAlertDialog.setMessage(message);
		mAlertDialog.show();
	}
}
